<template>
  <form class="form-horizontal">

    <div class="form-group">
      <label for="inputUsername" class="col-sm-2 col-xs-3 col-xs-offset-1 control-label">用户名</label>
      <div class="col-sm-3 col-xs-6">
        <input type="text"  v-model="username" class="form-control" id="inputUsername" placeholder="请输入用户名">
      </div>
    </div>

    <div class="form-group">
      <label for="inputPassword" class="col-sm-2 col-xs-3 col-xs-offset-1 control-label">密码</label>
      <div class="col-sm-3 col-xs-6">
        <input type="password" v-model="password" class="form-control" id="inputPassword" placeholder="请输入密码">
      </div>
    </div>
    
    <div class="form-group">
      <div class="col-sm-offset-3 col-sm-1 col-xs-offset-4">
        <img src="/captcha" style="width:100px; height:34px">
      </div>
    </div>

    <div class="form-group">
      <label for="inputCaptcha" class="col-sm-2 col-xs-3 col-xs-offset-1 control-label">验证码</label>
      <div class="col-sm-3 col-xs-6">
        <input type="text" v-model="captcha" class="form-control" id="inputCaptcha" placeholder="请输入验证码">
         
      </div>

    </div>

    

    <div class="container-fluid">
      <div class="row">
     
        <div class="col-sm-offset-3 col-sm-1 col-xs-offset-4 col-xs-1 ">
          <button @click.prevent="login" class="btn btn-default">登录</button>
        </div>
        
        <div class="col-sm-5 col-xs-5 col-xs-offset-1">
          <p v-show="hasError" class="text-danger">错误，请重新输入</p>
        </div>
        
      </div>
    </div>
          
  </form>
</template>

<script>

export default {
  data(){
    return {
      username:"",
      password:"",
      captcha:"",
      hasError:false,
    }
  },

  methods:{
    async login(){
      try {
        console.log("发送login请求")
        let res = await this.$http.post("/api/login",{
          username: this.username,
          password: this.password,
          captcha: this.captcha,
        })
        //改变根组件的数据，为啥显示没变啊，按道理要跟着变啊
        console.log(this.$root.$children)
        this.$root.$children[0].user = res.data.user

        this.$router.push('/')       
      } catch(e){
        this.hasError = true
      }
      //账号密码或者验证码错误时，服务器返回一个status(403)错误状态码，客户端会抛错
      
    }
  },
  
}
</script>

<style scoped>
  form{
    margin-top: 100px;
    
  }
</style>


